package com.terra.ns.imp.common.oss.minio

import io.minio.GetPresignedObjectUrlArgs
import io.minio.MinioClient
import io.minio.http.Method
import java.util.concurrent.TimeUnit

/**
@author qins
@date 2023/8/11
@desc
 */
class MinioUtils(private var minioClient: MinioClient, private var minioProperties: MinioProperties) {


    // 返回minio客户端
    fun getClient() = minioClient

    /**
     * 获取临时上传文件的Url
     * @param fileName 上传文件名
     * @param expiry url有效期 单位分钟 默认10分钟
     */
   fun getUploadUrl(fileName: String, expiry: Int = 10) : String {
       val reqParams = HashMap<String, String>()
       reqParams["response-content-type"] = "application/json"
       return minioClient
           .getPresignedObjectUrl(
               GetPresignedObjectUrlArgs.builder()
                   .method(Method.PUT)
                   .bucket(minioProperties.bucket)
                   .`object`(minioProperties.path + fileName)
                   .expiry(expiry, TimeUnit.MINUTES)
                   .extraQueryParams(reqParams)
                   .build()
           )
   }

    /**
     * 获取文件访问url
     */
    fun getFileAccessUrl(fileName: String) : String {
        return if(minioProperties.fileUrlPrefix.isNotBlank()) {
             minioProperties.fileUrlPrefix +  fileName
        } else {
          minioClient
            .getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                    .method(Method.GET)
                    .bucket(minioProperties.bucket)
                    .`object`(minioProperties.path + fileName)
                    .build()
            )
        }
    }

    // ... 其它方法封装
}